<template>
  <div class="mod-config">
    <el-steps :active="activeStep" finish-status="success" align-center>
      <el-step title="基本信息"></el-step>
      <el-step title="商品属性"></el-step>
      <el-step title="销售属性"></el-step>
      <el-step title="SKU信息"></el-step>
      <el-step title="保存完成"></el-step>
    </el-steps>

    <!-- 步骤一:基本信息 -->
    <el-form v-show="activeStep === 0" :model="baseForm" :rules="baseRules" ref="baseForm" label-width="120px">
      <el-form-item label="分类" prop="categoryId">
        <!-- <el-input v-model="dataForm.categoryId" placeholder="所属末级分类ID"></el-input> -->
        <category-cascader ref="categoryCascader" :categoryId="baseForm.categoryId" :catelogPath.sync="catelogPath"
          @getCategoryPath="getCategoryPath"></category-cascader>
        <!-- <category-cascader></category-cascader> -->
      </el-form-item>
      <el-form-item label="商品标题" prop="title">
        <el-input v-model="baseForm.title" placeholder="商品标题（含关键属性）"></el-input>
      </el-form-item>
      <el-form-item label="商品描述" prop="description">
        <el-input v-model="baseForm.description" placeholder="商品描述"></el-input>
      </el-form-item>
      <el-form-item label="主图" prop="mainImage">

        <singleUpload v-model="baseForm.mainImage"></singleUpload>
      </el-form-item>
      <el-form-item label="基础定价" prop="basePrice">
        <el-input type="number" v-model.number="baseForm.basePrice" placeholder="基础定价（单位：元）"></el-input>
      </el-form-item>

      <el-form-item label="商品banner" prop="bannerImgs">
        <multiUpload v-model="baseForm.bannerImgs" />
      </el-form-item>

      <el-form-item label="商品介绍" prop="descImgs">
        <multiUpload v-model="baseForm.descImgs" />
      </el-form-item>

      <el-form-item label="商品状态" prop="status">
        <el-select v-model="baseForm.status" placeholder="请选择">
          <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>



      <el-form-item>
        <el-button type="primary" @click="nextStep('baseForm')">下一步，填写商品属性</el-button>
      </el-form-item>
    </el-form>


    <!-- 步骤二:商品属性 -->
    <div v-show="activeStep === 1">
      <el-form :model="attrForm" ref="attrForm" label-width="120px">
        <el-table :data="attrForm.attrs" border style="width: 100%">
          <el-table-column label="属性名" prop="attributeName">
            <template slot-scope="scope">
              <el-input v-model="scope.row.attributeName" placeholder="请输入属性名"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="属性值" prop="attributeValue">
            <template slot-scope="scope">
              <el-input v-model="scope.row.attributeValue" placeholder="请输入属性值"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template slot-scope="scope">

              <el-button type="text" size="small" @click="deleteAttr(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-form-item>
          <el-button @click="addAttribute">添加属性</el-button>
          <el-button @click="prevStep">上一步，选择商品基本信息</el-button>
          <el-button type="primary" @click="nextStep('attrForm')">下一步，填写销售属性</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 步骤三:销售属性 -->
    <div v-show="activeStep === 2">
      <el-form :model="saleAttrForm" ref="saleAttrForm" label-width="120px">
        <el-table :data="saleAttrForm.attrs" border style="width: 100%">
          <el-table-column label="销售属性名" prop="attrName">
            <template slot-scope="scope">
              <el-input v-model="scope.row.attrName" placeholder="请输入销售属性名"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="销售属性值" prop="attributeValueArr">
            <template slot-scope="scope">
              <el-tag :key="tag" v-for="tag in scope.row.attributeValueArr" closable :disable-transitions="false"
                @close="handleClose(tag, scope.row)" style="margin-right: 10px;">
                {{ tag }}
              </el-tag>
              <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue"
                ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)"
                @blur="handleInputConfirm(scope.row)">
              </el-input>
              <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ 添加值</el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="deleteSaleAttr(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-form-item>
          <el-button @click="addSaleAttr">添加销售属性</el-button>
          <el-button @click="prevStep">上一步，填写商品属性</el-button>
          <el-button type="primary" @click="nextStep('saleAttrForm')">下一步，设置SKU信息</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 步骤四:SKU信息 -->
    <div v-show="activeStep === 3">
      <el-table :data="skuList" border>
        <el-table-column v-for="attr in saleAttrForm.attrs" :key="attr.attrName" :label="attr.attrName">
          <template slot-scope="{ row }">
            {{ findAttributeValue(row.SkuAttributeValueArr, attr.attrName) }}
          </template>
        </el-table-column>
        <el-table-column label="售价">
          <template slot-scope="{ row }">
            <el-input v-model.number="row.price" type="number"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="库存">
          <template slot-scope="{ row }">
            <el-input v-model.number="row.stock" type="number"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="SKU图片">
          <template slot-scope="{ row }">
            <singleUpload v-model="row.imgUrl"></singleUpload>
          </template>
        </el-table-column>
        <!-- <el-table-column label="SKU编码">
          <template slot-scope="{ row }">
            <el-input v-model="row.skuCode" placeholder="自动生成"></el-input>
          </template>
        </el-table-column> -->
      </el-table>
      <div class="button-group">
        <el-button @click="prevStep">上一步，设置销售属性</el-button>
        <el-button type="primary" @click="nextStep('skuForm')">下一步，完成</el-button>
      </div>
    </div>


    <!-- 步骤五:完成 -->
    <div v-show="activeStep === 4" class="success-info">
      <i class="el-icon-success"></i>
      <h2>点击完成提交商品信息!</h2>
      <div class="button-group">
        <el-button @click="prevStep">上一步，设置SKU信息</el-button>
        <el-button type="success" @click="finish">完成</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import CategoryCascader from "../common/category-cascader.vue";
import MultiUpload from "../common/upload/multiUpload.vue";
import singleUpload from "../common/upload/singleUpload.vue";
export default {
  components: { CategoryCascader, MultiUpload, singleUpload },
  data() {
    return {
      activeStep: 0,
      catelogPath: [],

      baseForm: {
        categoryId: '',
        title: '',
        description: '',
        mainImage: '',
        basePrice: null,
        status: 1,
        // viewCount: '',
        // createdAt: '',
        // updatedAt: '',
        // 轮播图图片集合
        bannerImgs: [],
        // 详情图图片集合
        descImgs: [],

      },
      attrForm: {
        attrs: [] // 存储商品属性
      },
      newAttr: { // 用于存储新添加的属性
        attributeName: '',
        attributeValue: ''
      },

      statusOptions: [{
        value: 1,
        label: '上架'
      }, {
        value: 0,
        label: '下架'
      }],
      baseRules: {
        categoryId: [
          { required: true, message: '所属末级分类ID不能为空', trigger: 'blur' }
        ],
        title: [
          { required: true, message: '商品标题（含关键属性）不能为空', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '商品描述不能为空', trigger: 'blur' }
        ],
        mainImage: [
          { required: true, message: '主图URL地址不能为空', trigger: 'blur' }
        ],
        basePrice: [
          { required: true, message: '基础定价（单位：元）请输入合理价格', trigger: 'blur', validator: this.checkPositiveNumber }
        ],
        status: [
          { required: true, message: '商品状态不能为空', trigger: 'blur' }
        ],
        // viewCount: [
        //   { required: true, message: '累计浏览量不能为空', trigger: 'blur' }
        // ],
        bannerImgs: [
          { required: true, message: '商品banner不能为空', trigger: 'blur', },
        ],
        descImgs: [
          { required: true, message: '商品介绍图片不能为空', trigger: 'blur', },
        ],
        // updatedAt: [
        //   { required: true, message: '最后修改时间不能为空', trigger: 'blur' }
        // ]
      },


      attrForm: {
        attrs: []
      },
      saleAttrForm: {
        attrs: []
      },
      skuList: []
    }
  },
  methods: {
    // 表单验证规则数字大于0
    checkPositiveNumber(rule, value, callback) {
      if (!value) {
        callback(new Error('请输入一个数字'));
      } else {
        // 尝试将输入的值转换为浮点数
        const num = parseFloat(value);
        if (isNaN(num)) {
          callback(new Error('请输入一个有效的数字'));
        } else if (num <= 0) {
          callback(new Error('请输入一个大于0的数字'));
        } else {
          callback();
        }
      }
    },

    // 获取分类路径
    getCategoryPath(paths) {
      console.log("子组件传递的选中分类数据", paths);

      this.baseForm.categoryId = paths[paths.length - 1]
    },

    // 添加属性
    addAttribute() {
      this.attrForm.attrs.push({ attributeName: '', attributeValue: '' });
    },


    // 删除属性
    deleteAttr(index) {
      this.attrForm.attrs.splice(index, 1);
    },

    // 添加销售属性
    addSaleAttr() {
      this.saleAttrForm.attrs.push({
        attrName: '',
        attributeValueArr: [],
        inputVisible: false,
        inputValue: ''
      });
    },

    // 删除销售属性
    deleteSaleAttr(index) {
      this.saleAttrForm.attrs.splice(index, 1);
    },

    // 显示输入框
    showInput(row) {
      row.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    // 处理输入确认
    handleInputConfirm(row) {
      let inputValue = row.inputValue;
      if (inputValue && row.attributeValueArr.indexOf(inputValue) === -1) {
        row.attributeValueArr.push(inputValue);
      }
      row.inputVisible = false;
      row.inputValue = '';
    },

    // 删除标签
    handleClose(tag, row) {
      row.attributeValueArr.splice(row.attributeValueArr.indexOf(tag), 1);
    },

    // 下一步
    nextStep(formName) {
      console.log("formName", formName);

      if (formName) {
        if (formName === 'baseForm') {
          this.$refs[formName].validate((valid) => {
            if (valid) {
              this.activeStep++
            } else {
              return false
            }
          })
          // 步骤一验证逻辑
        }

        // 步骤二验证逻辑
        if (formName === 'attrForm') {
          if (this.attrForm.attrs.length === 0) {
            this.$message.error('至少需要添加一个商品属性');
            return;
          }
          const hasEmpty = this.attrForm.attrs.some(
            item => !item.attributeName.trim() || !item.attributeValue.trim()
          );
          if (hasEmpty) {
            this.$message.error('请填写完整的属性名称和值');
            return;
          }
          this.activeStep++
        }
        // 步骤三销售属性验证
        if (formName === 'saleAttrForm') {
          if (this.saleAttrForm.attrs.length === 0) {
            this.$message.error('至少需要添加一个销售属性');
            return;
          }
          const hasInvalid = this.saleAttrForm.attrs.some(
            item => !item.attrName.trim() || item.attributeValueArr.length === 0
          );
          if (hasInvalid) {
            this.$message.error('请填写完整的销售属性名称并添加至少一个属性值');
            return;
          }

          this.generateSkus();
          this.activeStep++
        }

        // 步骤四SKU信息验证
        // 步骤四SKU信息验证
        if (formName === 'skuForm') {
          if (this.skuList.length === 0) {
            this.$message.error('至少需要生成一个SKU');
            return;
          }


          console.log("skuList", this.skuList);

          const hasInvalidSku = this.skuList.some(sku =>
            Number(sku.price) > 0 &&
            Number(sku.stock) >= 0 &&
            sku.imgUrl.trim() !== ''

          );

          if (!hasInvalidSku) {
            this.$message.error('请检查：价格>0，库存≥0，图片不能为空');
            return;
          }


          this.activeStep++;
        }



      } else {
        this.activeStep++
      }
    }
    ,
    // 上一步
    prevStep() {
      this.activeStep--
    },
    // 完成
    finish() {
      this.$confirm('确认提交商品信息?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {

        console.log("baseForm", this.baseForm);
        console.log("attrForm", this.attrForm);
        console.log("saleAttrForm", this.saleAttrForm);
        console.log("skuList", this.skuList);

        this.$http({
          url: this.$http.adornUrl("/product/product/save"),
          method: "post",
          data: this.$http.adornData({
            ...this.baseForm,
            attrs: this.attrForm.attrs,
            skuAttrs: this.saleAttrForm.attrs,
            skuList: this.skuList
          })
        }).then(({ data }) => {
          if (data.code == 0) {
            this.$message({
              type: "success",
              message: "新增商品成功!"
            });
            // this.step = 4;
          } else {
            this.$message({
              type: "error",
              message: "保存失败，原因【" + data + "】"
            });
          }
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消提交'
        })
      })
    },

    // 新增生成SKU方法
    generateSkus() {
      this.skuList = []
      const saleAttrs = this.saleAttrForm.attrs.filter(attr => attr.attributeValueArr.length > 0);
      if (saleAttrs.length === 0) {
        this.skuList = [this.createEmptySku()];
        return;
      }

      const valueArrays = saleAttrs.map(attr => attr.attributeValueArr);
      const combinations = this.cartesianProduct(valueArrays);

      this.skuList = combinations.map(values => {
        const SkuAttributeValueArr = saleAttrs.map((attr, index) => ({
          attrName: attr.attrName,
          value: values[index]
        }));

        return {
          // skuId: null,
          // productId: null, // 保存商品后需要回填
          SkuAttributeValueArr,
          price: this.baseForm.basePrice || 0,
          stock: 0,
          // sales: 0,
          // skuCode: this.generateSkuCode(values),
          imgUrl: ''
        };
      });
    },

    // 笛卡尔积计算
    cartesianProduct(arr) {
      return arr.reduce((a, b) =>
        a.flatMap(x =>
          b.map(y => [...x, y])
        ),
        [[]]);
    },

    // 创建空SKU
    createEmptySku() {
      return {
        // skuId: null,
        // productId: null,
        SkuAttributeValueArr: [],
        price: this.baseForm.basePrice || 0,
        stock: 0,

        imgUrl: ''
      };
    },

    // 辅助方法：查找属性值
    findAttributeValue(SkuAttributeValueArr, attrName) {
      const attr = SkuAttributeValueArr.find(a => a.attrName === attrName);
      return attr ? attr.value : '';
    },

    // 生成SKU编码
    // generateSkuCode(values) {
    //   const timestamp = new Date().getTime().toString().slice(-4);
    //   return values.join('').substr(0, 6) + timestamp;
    // }
  },

  created() {

  }
}
</script>

<style scoped>
.el-form-item>>>.el-input__inner {
  width: 300px;
  /* 根据需要调整宽度 */
}


.mod-config {
  padding: 20px;
}


.el-steps {
  margin-bottom: 40px;
}

.button-group {
  margin-top: 20px;
  text-align: center;
}

.success-info {
  text-align: center;
  padding: 40px 0;
}

.success-info i {
  font-size: 60px;
  color: #67C23A;
}

.success-info h2 {
  margin-top: 20px;
  color: #67C23A;
}

.el-form-item {
  margin-bottom: 22px;
}
</style>
